import {browser} from "$app/environment";
import {seletedRoute,menuItems} from "$lib/stores/globalControl.svelte.js";
import {page} from "$app/state";
import {localInfo} from "$lib/stores/Storage.svelte.js";

export async function loadMenu() {
    let menu = [];
    menuItems.subscribe(value => {
        menu = value;
    })

    let local = [];
    localInfo.subscribe(value => {
        local = value;
    })

    //运行在浏览器中的
    if(browser) {

        let roleResponse = await fetch(`http://localhost:3000/roles/${local[0].role}`);
        let roleIds = [];
        if(roleResponse.ok){
            roleIds = await roleResponse.json();
            roleIds = roleIds?.list;
        }

        async function getMenu() {
            const promises = roleIds.map(menuId =>
                fetch(`http://localhost:3000/menu/${menuId}`)
                    .then(response => response.ok ? response.json() : null)
                    .catch(() => null)
            );

            //所有的 异步对象 全部执行完毕
            const menus = await Promise.all(promises);
            return menus.filter(Boolean); //过滤掉失败的请求
        }


        getMenu().then(m=>{
            menuItems.set(m);
        }).finally(()=>{
            menuActive();
        });

        function menuActive() {
            let parentItem = menu.filter(obj => {
                return !obj?.parent
            })

            let childItem = menu.filter(obj => {
                return obj?.parent
            })

            parentItem.forEach(parent => {
                parent['children'] = [];
                childItem.forEach(child => {
                    if (child.parent === parent.id) {
                        parent['children'].push(child);
                    }
                })
            })

            menuItems.set(parentItem);
        }

        //加载面包屑
        seletedRoute.set(page.url.pathname);
    }
}